package com.hx.thread.syclicbarrier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author Minghua Chen
 * @date 2020-09-05 23:36
 */
public class CyclicBarrierDemo {
    private static final Logger logger = LoggerFactory.getLogger(CyclicBarrierDemo.class);

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3/*,() -> logger.info("凑齐三人,开始出发")*/);
        for (int i = 0; i < 5; i++) {
            new Thread(new Task(i + 1, barrier)).start();
        }
    }

    static class Task implements Runnable {
        private int id;
        private CyclicBarrier barrier;

        public Task(int id, CyclicBarrier barrier) {
            this.id = id;
            this.barrier = barrier;
        }

        @Override
        public void run() {
            logger.info("同学" + id + "从大门出发,前往自行车驿站");
            try {
                Thread.sleep((long) (Math.random()) * 10000);
                logger.info("同学" + id + "到达自行车驿站,等待组队");
                // 回到0之后会重新计数  线程的数量如果不是 barrier的倍数 是会阻塞的
                barrier.await();
                logger.info("同学" + id + "开始骑自行车");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
